using System;
using System.IO;
using System.Collections.Generic;
using MSOutlook = Microsoft.Office.Interop.Outlook;

namespace Microsoft.Sample.Outlook.Utility
{
    public sealed class Folder
	{
		/// <summary>
		/// Returns a reference to a child folder of a folder with a specific name, creating an inbox folder if it doesn't exist.
		/// </summary>
		/// <param name="root"></param>
		/// <param name="folderName"></param>
		/// <returns></returns>
		public static MSOutlook.MAPIFolder CreateFolder(MSOutlook.MAPIFolder root, string folderName)
		{
            return CreateFolder(root, folderName, MSOutlook.OlDefaultFolders.olFolderInbox);
		}

		/// <summary>
		/// Returns a reference to a child folder of a folder with a specific name, creating it if it doesn't exist
		/// </summary>
		/// <param name="root"></param>
		/// <param name="folderName"></param>
		/// <param name="folderType"></param>
		/// <returns></returns>
		public static MSOutlook.MAPIFolder CreateFolder(MSOutlook.MAPIFolder root, string folderName, MSOutlook.OlDefaultFolders folderType)
		{
			MSOutlook.MAPIFolder folder = GetFolder(root, folderName);
			if (folder == null)
				folder = AddChildFolder(root, folderName, folderType);

			return folder;
		}

		/// <summary>
		/// Returns a reference to a child folder of a folder with a specific name, returning null if it doesn't exist
		/// </summary>
		/// <param name="root"></param>
		/// <param name="folderName"></param>
		/// <returns></returns>
		public static MSOutlook.MAPIFolder GetFolder(MSOutlook.MAPIFolder root, string folderName)
		{
			foreach (MSOutlook.MAPIFolder f in root.Folders)
			{
				if (f.Name == folderName)
					return f;
			}

			return null;
		}

		public static MSOutlook.MAPIFolder GetRootFolder(MSOutlook.NameSpace session)
		{
			return (MSOutlook.MAPIFolder)session.GetDefaultFolder(
                    MSOutlook.OlDefaultFolders.olFolderInbox).Parent;
		}
		
		/// <summary>
		/// Creates a child inbox folder with the specified name 
		/// </summary>
		/// <param name="root"></param>
		/// <param name="folderName"></param>
		/// <returns></returns>
		public static MSOutlook.MAPIFolder AddChildFolder(MSOutlook.MAPIFolder root, string folderName)
		{
            return AddChildFolder(root, folderName, MSOutlook.OlDefaultFolders.olFolderInbox);
		}

		/// <summary>
		/// Creates a child folder with the specified name of the specified folder type
		/// </summary>
		/// <param name="root"></param>
		/// <param name="folderName"></param>
		/// <param name="folderType"></param>
		/// <returns></returns>
        public static MSOutlook.MAPIFolder AddChildFolder(MSOutlook.MAPIFolder root, string folderName, MSOutlook.OlDefaultFolders folderType)
		{
			return root.Folders.Add(folderName, folderType);
		}



	}
}
